package com.qipay.ips.service.impl;


import com.qipay.baas.model.User;
import com.qipay.baas.model.WhiteIps;
import com.qipay.baas.model.WhiteIpsExample;
import com.qipay.ips.service.IpsService;
import com.qipay.mapper.WhiteIpsMapper;
import com.qipay.security.UserDetailsServiceImpl;
import com.qipay.user.service.UserService;
import com.qipay.utils.CommonUtil;
import com.qipay.utils.IPUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.net.util.IPAddressUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class IpsServiceImpl implements IpsService {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    WhiteIpsMapper whiteIpsMapper;

    @Autowired
    UserService userService;

    @Override
    public void add(UserDetailsServiceImpl.LoginUserDetails loginUser, String ipAddress) {
        long cpId = loginUser.getCpId();
        WhiteIps whiteIps = new WhiteIps();
        whiteIps.setCpid(cpId);
        whiteIps.setIpAddress(ipAddress);
        whiteIpsMapper.insert(whiteIps);
    }

    @Override
    public void delete(UserDetailsServiceImpl.LoginUserDetails loginUser, long id) {
        int result = whiteIpsMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteSome() {
    }

    @Override
    public List<WhiteIps> query(UserDetailsServiceImpl.LoginUserDetails loginUser) {
        long cpId = loginUser.getCpId();
        return query(cpId);
    }

    private List<WhiteIps> query(final long cpId) {
        WhiteIpsExample whiteIpsExample = new WhiteIpsExample();
        whiteIpsExample.or().andCpidEqualTo(cpId);
        List<WhiteIps> whiteIps = whiteIpsMapper.selectByExample(whiteIpsExample);
        return whiteIps;
    }

    @Override
    public boolean checkIp(String userName, HttpServletRequest request) {
        //不是商户,直接通过
        User user = userService.getByName(userName);
        if (user.getLevel() != 1 && user.getLevel() != 200) return true;

        String ip = IPUtils.getIpAddr(request);
        logger.info("本次获取的ip是："+ip);
        List<WhiteIps> whiteIps = query(Long.parseLong(userName));
        if (whiteIps.size() == 0) return true;

        //找出是否有白名单
        long count = whiteIps.stream().filter(item -> CommonUtil.equalsString(item.getIpAddress(), ip)).count();
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean isNotWhiteIp(String userName) {
        //不是商户,直接通过
        User user = userService.getByName(userName);
        if (user.getLevel() != 1 && user.getLevel() != 200) return false;

        List<WhiteIps> whiteIps = query(Long.parseLong(userName));
        if (CommonUtil.isEmpty(whiteIps)) {
            return true;
        }
        return false;
    }
}
